package com.yc.fav.web;

import com.yc.fav.Utils;
import com.yc.fav.entity.User;
import com.yc.fav.service.BizException;
import com.yc.fav.service.IUserService;
import com.yc.fav.vo.Result;
import org.springframework.context.ApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/reg")
public class RegServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Result result = new Result();
        ApplicationContext cxt = (ApplicationContext)this.getServletContext().getAttribute("cxt");
        String name = req.getParameter("name");
        String pwd = req.getParameter("pwd");
        String email = req.getParameter("email");
        String head = req.getParameter("head");
        if(head == null || "".equals(head)){
            head ="https://img1.baidu.com/it/u=2307902938,771588540&fm=253&fmt=auto&app=120&f=JPEG?w=507&h=500";
        }
        User user = new User();
        user.setName(name);
        user.setHead(head);
        user.setEmail(email);
        user.setPwd(pwd);
        IUserService as = cxt.getBean(IUserService.class);
        try {
            as.reg(user);
            result.setCode(1);
            result.setMsg("注册成功");
        } catch (BizException e) {
            result.setCode(-1);
            result.setMsg(e.getMessage());
        }catch (RuntimeException e){
            result.setCode(-2);
            result.setMsg("系统繁忙");
        }finally {
            Utils.print(resp,result);
        }
    }
}
